package com.he.hsdyc.config.Queue;

import com.he.hsdyc.common.constant.AMQPConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class AMQPConfig {
    private static final Logger logger = LoggerFactory.getLogger(AMQPConfig.class);
//    /**
//     * 消息队列（测试）
//     */
//    @Bean
//    public Queue testConfig() {
//        logger.info("=============打开AMQP-"+ AMQPConstant.QUEUES_TEST_CONFIG);
//        return new Queue(AMQPConstant.QUEUES_TEST_CONFIG);
//    }



    /**
     * 正常队列（即消息过期后由延时队列自动转发到的正常队列）
     */
    //正常队列名称常量设置
    public static final String ORDER_QUEUE_NAME = "tao.order.queue";
    public static final String ORDER_EXCHANGE_NAME = "tao.order.exchange";
    public static final String ORDER_ROUTING_KEY = "order";

    //定义正常queue,Exchange,route-key之间的绑定关系
    @Bean
    public Queue orderQueue() {
        return new Queue(ORDER_QUEUE_NAME, true);
    }
    @Bean
    public TopicExchange orderTopicExchange() {
        return new TopicExchange(ORDER_EXCHANGE_NAME);
    }
    @Bean
    public Binding orderBinding() {
        // 如果要让延迟队列之间有关联,这里的 routingKey 和 绑定的交换机很关键
        return BindingBuilder.bind(orderQueue()).to(orderTopicExchange()).with(ORDER_ROUTING_KEY);
    }




    /**
     * 延时队列
     */
    //延时队列名称常量相关设置
    private static final String ORDER_DELAY_QUEUE = "tao.order.delay.queue";
    public static final String ORDER_DELAY_EXCHANGE = "tao.order.delay.exchange";
    public static final String ORDER_DELAY_ROUTING_KEY = "order_delay";


    //定义延时queue,Exchange,route-key之间的绑定关系
    //并且设置消息过期后的转发的死信队列以及route-key
    @Bean
    public Queue delayOrderQueue() {
        Map<String, Object> params = new HashMap<>();
        // x-dead-letter-exchange 声明了队列里的死信转发到的DLX名称，
        params.put("x-dead-letter-exchange", ORDER_EXCHANGE_NAME);
        // x-dead-letter-routing-key 声明了这些死信在转发时携带的 routing-key 名称。
        params.put("x-dead-letter-routing-key", ORDER_ROUTING_KEY);
        return new Queue(ORDER_DELAY_QUEUE, true, false, false, params);
    }
    @Bean
    public DirectExchange orderDelayExchange() {
        return new DirectExchange(ORDER_DELAY_EXCHANGE);
    }
    @Bean
    public Binding dlxBinding() {
        return BindingBuilder.bind(delayOrderQueue()).to(orderDelayExchange()).with(ORDER_DELAY_ROUTING_KEY);
    }

}